<template>
  <div class="md-image-upload-base">
    <div class="upload-container">
      <template v-if="!multiple">
        <el-upload :headers="headers" :data="params" :disabled="disabled" :action="action" :show-file-list="false" :on-success="handleSuccess" :before-upload="handleBefore">
          <template>
            <div class="upload-box" :style="{width: width, height: height}">
              <img class="avatar" ref="img" v-if="src" :src="src" />
              <div v-else>
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <p>{{label}}</p>
              </div>
            </div>
          </template>
        </el-upload>
      </template>

      <template v-if="multiple">
        <div class="img-list">
          <div class="img-list-item" v-for="(item, index) in srcList" :key="index" :style="{width: width, height: height}">
            <el-image class="avatar" :src="item" :preview-src-list="srcList" lazy />
            <i class="el-icon-delete" @click="handleImgRemove(item, index)"></i>
          </div>
          <div class="img-list-item">
            <el-upload :headers="headers" :data="params" :disabled="disabled" :action="action" multiple :show-file-list="false" :on-success="handleSuccess" :before-upload="handleBefore">
              <template>
                <div class="upload-box" :style="{width: width, height: height}">
                  <div>
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                    <p>{{label}}</p>
                  </div>
                </div>
              </template>
            </el-upload>
          </div>
        </div>
      </template>
    </div>

    <div style="font-size: 12px; color: #f00;">
      <p>请上传 {{exts.join(',')}} 格式文件！文件大小 {{size}}{{sizeUnit}}！{{desc}}</p>
    </div>
  </div>
</template>

<script>
import { mdApiBase } from '@/ddd/config.service.js'
import { _dataEncryption } from '@/ddd/encryption.service.js'
import { Message } from 'element-ui'
export default {
  name: 'MdImageUploadBaseComponent',
  props: {
    value: [String, Array],
    /** 请求参数 */
    params: {
      type: Object,
      default: () => {
        return {}
      }
    },
    /** 请求地址 */
    action: {
      type: String,
      default: `${mdApiBase}/util/upload/localSingle`
    },
    /** 缺省文本信息 */
    label: {
      type: String,
      default: '上传封面'
    },
    /** 容器宽度 */
    width: {
      type: String,
      default: '150px'
    },
    /** 容器高度 */
    height: {
      type: String,
      default: '150px'
    },
    /** 文件扩展名 */
    exts: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    /** 文件大小 */
    size: {
      default: '10'
    },
    /** 文件大小单位 */
    sizeUnit: {
      default: 'MB'
    },
    /** 描述信息：如图片尺寸描述等 */
    desc: {
      type: String,
      default: null
    },
    /** 是否支持多文件选择 */
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      src: this.value,
      srcList: this.value,
      headers: {
        Authorization: `Bearer ${this.$local.getItem('Authorization')}`
      },
      disabled: false,
      partProgress: 0, // 分片进度
      partList: [], // 分片集合
      loading: null
    }
  },
  watch: {
    value: {
      handler (val) {
        this.handleSetValue(val)
      },
      deep: true
    }
  },
  mounted () {
    this.handleSetValue(this.value)
  },
  methods: {
    /** 设置值 */
    handleSetValue (val) {
      this.$nextTick(() => {
        const model = {}
        const signModel = _dataEncryption(model)
        this.params.merchantId = signModel.merchantId
        this.params.ip = signModel.ip
        this.params.mac = signModel.mac
        this.params.isValid = signModel.isValid
        this.params.version = signModel.version
        this.params.timesTamp = signModel.timesTamp
        this.params.token = signModel.token
        this.params.sign = signModel.sign

        if (!this.multiple) {
          this.src = val
        } else {
          this.srcList = val
        }
      })
    },
    /** 上传前验证 */
    handleBefore (file) {
      this.loading = this.$loading({ text: this.part ? '队列中...' : '上传中...' })

      const isMB = file.size / 1024 / 1024 < this.size;

      if (!isMB) {
        this.$message.error(`上传图片大小不能超过 ${this.size}${this.sizeUnit}!`)
        if (this.loading) this.loading.close()
        return false
      }

      const isExt = this.exts.includes((file.name.split('.').pop()).toLowerCase())

      if (!isExt) {
        this.$message.error(`上传图片格式：${this.exts.join(',')}!`)
        if (this.loading) this.loading.close()
        return false
      }

      return true
    },
    handleImgRemove (src, index) {
      const list = this.srcList

      list.splice(index, 1)

      this.$emit('input', list)
      this.$emit('change', { val: list })
    },
    /** 上传成功回调 */
    async handleSuccess (res) {
      if (res.code === '200') {
        if (!this.multiple) {
          this.src = res.data.url
          this.$emit('input', this.src)
          this.$emit('change', { val: this.src, res: res.data })
        } else {
          this.srcList.push(res.data.url)
          this.$emit('input', this.srcList)
          this.$emit('change', { val: this.srcList })
        }
      } else {
        Message.error(res.msg)
      }

      if (this.loading) this.loading.close()
    }
  }
}
</script>

<style lang="less" scoped>
.md-image-upload-base {
  width: 100%;

  .upload-container {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .img-list {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .img-list-item {
        border: 1px dashed #d9d9d9;
        border-radius: 0px;
        cursor: pointer;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        margin-bottom: 10px;
        .el-icon-delete {
          position: absolute;
          top: -10px;
          right: -10px;
          background-color: rgba(0, 0, 0, 0.3);
          color: #fff;
          padding: 5px;
          border-radius: 50%;
          z-index: 100;
          cursor: pointer;
          display: none;
        }
        &:hover {
          .el-icon-delete {
            display: block;
          }
        }
        ::v-deep .avatar {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            display: block;
            width: auto;
            height: auto;
            max-width: 100%;
            max-height: 100%;
          }
        }

        ::v-deep .el-upload {
          .upload-box {
            border: none !important;
          }
        }
      }
    }
    ::v-deep .el-upload {
      width: 100%;
      display: flex;
      align-items: center;
      .upload-box {
        border: 1px dashed #d9d9d9;
        border-radius: 0px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        i {
          font-size: 30px;
          color: #8c939d;
        }
        .avatar {
          display: block;
          width: auto;
          height: auto;
          max-width: 100%;
          max-height: 100%;
        }
        .part-progress {
          width: 100%;
          height: 2px;
          position: absolute;
          bottom: 0px;
          left: 0px;
          .progress-box {
            height: 100%;
            background-color: #67c23a;
          }
        }
      }
    }
  }
}
</style>